package com.hou.zookeeper.zkclient;

import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.ZkConnection;
import org.apache.zookeeper.CreateMode;

import java.util.List;

public class Zk01 {
    /**
     * zookeeper地址
     */
    static final String CONNECT_ADDR = "192.168.171.128:2181,192.168.171.129:2181,192.168.171.130:2181";
    /**
     * session超时时间
     */
    static final int SESSION_OUTTIME = 5000;//ms

    public static void main(String[] args) {
        // 创建zkclient实例
        ZkClient zkc = new ZkClient(new ZkConnection(CONNECT_ADDR, SESSION_OUTTIME), 10000);
        //增
        zkc.create("/test", "测试zkclient", CreateMode.PERSISTENT);// 创建节点,可指定持久或者临时
        zkc.create("/test/heyi", "heyi", CreateMode.PERSISTENT);// 创建节点,可指定持久或者临时
        zkc.createEphemeral("/haha", "haha");//创建临时节点
        zkc.createPersistent("/test/yaozhen", "姚振");//创建持久节点,设置值必须有父节点
        zkc.createPersistent("/320/houzheng", true);//支持递归创建,但是不能设置值,否则会报异常
        //删
        zkc.delete("/test/yaozhen");
        zkc.deleteRecursive("/320");//递归删除,会删除节点下的子节点
        //改
        zkc.writeData("/test", "新内容");
        //查
        boolean exists = zkc.exists("/test");
        System.out.println(exists);
        zkc.readData("/jim", true);//如果节点为空返回null
        String readData = zkc.readData("/test");
        System.out.println(readData);
        //获取子节点和阅读子节点数据
        List<String> list = zkc.getChildren("/test");
        for (String p : list) {
            System.out.println(p);
            String rp = "/test/" + p;
            String data = zkc.readData(rp);
            System.out.println("节点为：" + rp + "，内容为: " + data);
        }
        int i = zkc.countChildren("/test");//查询子节点数量
        System.out.println(i);
    }
}
